'use strict';

const db = uniCloud.database()
const bannersCollection = db.collection('banners')

exports.main = async (event, context) => {
	try {
		const { page = 1, pageSize = 10, keyword = '' } = event
		
		// 构建查询条件
		const query = {}
		if (keyword) {
			// 使用正则表达式进行模糊搜索
			const regex = new RegExp(keyword, 'i')
			query.title = regex
		}
		
		// 获取总数
		const total = await bannersCollection.where(query).count()
		
		// 获取分页数据
		const list = await bannersCollection
			.where(query)
			.skip((page - 1) * pageSize)
			.limit(pageSize)
			.orderBy('createTime', 'desc')
			.get()
		
		return {
			code: 0,
			msg: '获取成功',
			data: {
				list: list.data,
				total: total.total
			}
		}
	} catch (error) {
		console.error('获取轮播图列表失败', error)
		return {
			code: -1,
			msg: '获取失败',
			data: null
		}
	}
} 